/**
 *	Copyright (c) 2009, SpLib.net
 * 	All rights reserved.
  	
 * 	Author:6spring
 * 	About:Singleton工厂，持有每个Singleton的引用，避免模块卸载时被意外删除
*/

package SpLib.Com
{
	import SpLib.std.iterator;
	import SpLib.std.map;
	
	public final class SingletonFactory
	{
		private static var s_Instance:SingletonFactory = null;
		private var m_szSingleton:SpLib.std.map = new SpLib.std.map();
		
		public static function GetInstance():SingletonFactory
		{
			if(s_Instance==null)
			{
				s_Instance = new SingletonFactory();
			}
			
			return s_Instance;
		}
		
		public function SingletonFactory()
		{
			if(s_Instance!=null)
			{
				throw new Error("SingletonFactory is Singleton");
			}
		}
	
		public static function Get(name:String):*
		{
			var ins:SingletonFactory = GetInstance();
			
			var iter:SpLib.std.iterator = ins.m_szSingleton.find(name);
			if(iter!=ins.m_szSingleton.end())
			{
				return iter.m_Data;
			}
			
			return null;
		}
		
		public static function Reg(name:String,pObj:*):Boolean
		{
			var ins:SingletonFactory = GetInstance();
			
			var iter:SpLib.std.iterator = ins.m_szSingleton.find(name);
			if(iter!=ins.m_szSingleton.end())
			{
				return iter.m_Data===pObj;
			}
			
			ins.m_szSingleton.insert(name,pObj);
			return true;
		}
		
		public static function UnReg(name:String,pObj:*):Boolean
		{
			var ins:SingletonFactory = GetInstance();
			
			var iter:SpLib.std.iterator = ins.m_szSingleton.find(name);
			if(iter!=ins.m_szSingleton.end())
			{
				if(iter.m_Data===pObj)
				{
					ins.m_szSingleton.erase(iter);
					return true;
				}
			}
			
			return false;
		}
	}
}